// @ts-ignore
import { Effect, Reducer, Subscription, request } from 'umi';
import { uniqueArr } from '@/utils';

export interface PlayerModelState {
  songIdList: any;
  songData: any[];
}

export interface PlayerModelType {
  namespace: 'playerModel';
  state: PlayerModelState;
  effects: any;
  reducers: any;
  subscriptions: any;
}

const playerModel: PlayerModelType = {
  namespace: 'playerModel',

  state: {
    songIdList: window.localStorage.getItem('songIdList')
      ? window.localStorage.getItem('songIdList')
      : [],
    songData: [],
  },

  effects: {
    *getSongIdList({ type, payload }: any, { put, call, select }: any) {
      let result: any = [];
      if (window.localStorage.getItem('songIdList') != null) {
        let arr: any = window.localStorage.getItem('songIdList');
        result = result.concat(arr.split(','), payload.idList);
      } else {
        result = payload.idList;
      }
      console.log(uniqueArr(result));
      if (uniqueArr(result).length > 0) {
        yield put({
          type: 'getSongData',
          payload: {
            songIdList: uniqueArr(result).toString(),
          },
        });
      }
      window.localStorage.setItem('songIdList', uniqueArr(result));
      yield put({
        type: 'saveSongIdList',
        payload: {
          songIdList: uniqueArr(result),
        },
      });
    },
    *getSongData({ type, payload }: any, { put, call, select }: any) {
      let data = yield request(`/song/detail?ids=${payload.songIdList}`);
      let songUrlList = yield request(`/song/url?id=${payload.songIdList}`);
      let songDetailList = data.songs;
      songDetailList.forEach((item: any) => {
        songUrlList.data.forEach((item1: any) => {
          if (item.id == item1.id) {
            item.songUrl = item1.url;
          }
        });
      });
      yield put({
        type: 'saveSongData',
        payload: {
          songData: data.songs,
        },
      });
      return data.songs;
    },
  },
  reducers: {
    saveSongIdList(state: any, action: any) {
      return {
        ...state,
        ...action.payload,
      };
    },
    saveSongData(state: any, action: any) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
  subscriptions: {},
};

export default playerModel;
